import { config } from '../config.js'

class Http {
  constructor() {
    this.baseRestUrl = config.base_rest_url,
    this.appkey = config.appkey
  }

  request(params) {
    var that = this
    var url = this.baseRestUrl + params.url
    var appkey = this.appkey
    var userToken = getApp().globalData.userToken
    var requestData = params.data
    if (!params.method) {
      params.method = 'GET'
    }
    wx.request({
      url: url,
      data: requestData,
      method: params.method,
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        "User-Token": userToken,
        "Api-Appkey": appkey
      },
      success: function (res) {
        // 判断以2（2xx)开头的状态码为正确
        // 异常不要返回到回调中，就在request中处理，记录日志并showToast一个统一的错误即可
        var code = res.statusCode.toString()
        var startChar = code.charAt(0)
        if (startChar == '2' && res.data.code == 0) {
          params.success && params.success(res)
        } else {
          if (startChar == '4') {
            res.data.message = "客户端异常，请重试"
          } else if (startChar != '2' || startChar == '5') {
            res.data.message = "服务器异常，请重试"
          }
          params.error && params.error(res)
        }
      },
      fail: function (err) {
        params.fail && params.fail(err)
      }
    })
  }

  sendHttp(url, params, method) {
    var that = this
    this.request({
      url: url,
      data: params.data,
      method: method,
      success: function (res) {
        params.success && params.success(res)
        params.finish && params.finish()
      },
      error: function (res) {
        var code = res.data.code
        if (code == 1100) {
          wx.removeStorage({key: 'userToken'})
          getApp().globalData.userToken = ''
          wx.showModal({
            title: '提示',
            content: '用户未登录',
            confirmText: '去登录',
            success: function (res) {
              if (res.confirm) {
                wx.navigateTo({
                  url: '/pages/system/login/login',
                })
              }
            }
          })
        } else {
          that.showError(res.data.message)
        }
        params.finish && params.finish()
      },
      fail: function (res) {
        that.showError("小程序异常，请重试")
        params.finish && params.finish()
      }
    })
  }

  showError(msg) {
    wx.showToast({
      title: msg,
      icon: 'none'
    })
  }
}

export { Http }